package com.thunder.reader.ui;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.thunder.reader.FeedSettings;
import com.thunder.reader.R;
import com.thunder.reader.provider.Feed;
import com.thunder.reader.transaction.Transaction;
import com.thunder.reader.transaction.TransactionService;
import com.thunder.reader.ui.ArticleListActivity.OnContentChangedListener;

public class GroupListActivity extends ListActivity {
    private static final String TAG = "GroupListActivity";
    private AsyncGroupQueryHandler mQueryHandler;
    private GroupListAdapter mListAdapter;
    private static final int TOKEN_QUERY_ALL_GROUP = 0;
    
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setTitle(R.string.label_group);
        mQueryHandler = new AsyncGroupQueryHandler(getContentResolver());
        getListView().setOnCreateContextMenuListener(mContextMenu);
        mListAdapter = new GroupListAdapter(getApplication(), null);
        mListAdapter.addContentChangedListener(new OnContentChangedListener() {
            public void onContentChanged() {
                startAsyncQuery();
            }
        });
        setListAdapter(mListAdapter);
        startAsyncQuery();
    }
  
    @Override
    public void onResume() {
        super.onResume();
        Log.e(TAG, "resuming, resuming");
    }
    
    @Override
    public void onPause() {
        super.onPause();
        Log.e(TAG, "pauinging, pausing");
    }
    
    private OnCreateContextMenuListener mContextMenu = new OnCreateContextMenuListener() {
        public void onCreateContextMenu(ContextMenu menu, View v,
                ContextMenuInfo info) {
            final Uri groupUri = ContentUris.withAppendedId(Feed.Group.CONTENT_URI, ((AdapterContextMenuInfo) info).id);
            final Cursor cursor = getContentResolver().query(groupUri, new String[]{Feed.Group.TITLE}, 
                    null, null, null);
            if (cursor == null || !cursor.moveToFirst()) {
                return;
            }
            getMenuInflater().inflate(R.menu.group_list_contextmenu, menu);
            menu.setHeaderTitle(cursor.getString(0));
            cursor.close();
        }
    };
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        final AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
        case R.id.group_list_contextmenu_edit: {
            final Intent intent = new Intent(getApplication(), AddGroupActivity.class);
            intent.putExtra(AddGroupActivity.EXTRA_GROUP_ID, menuInfo.id);
            startActivity(intent);
            break;
        }
        case R.id.group_list_contextmenu_delete: {
            final Intent intent = new Intent(getApplication(), DeleteItemActivity.class);
            intent.putExtra(DeleteItemActivity.EXTRA_GROUP_ID, menuInfo.id);
            startActivity(intent);
            break;
        }
        case R.id.group_list_contextmenu_mark_as_read: {
            final ContentValues cv = new ContentValues();
            cv.put(Feed.Article.READ, 1);
            getContentResolver().update(Feed.Article.CONTENT_URI, cv, 
                    Feed.Article.GROUP_ID + "=?", new String[]{String.valueOf(menuInfo.id)});
            break;
        }
        case R.id.group_list_contextmenu_mark_as_unread: {
            final ContentValues cv = new ContentValues();
            cv.put(Feed.Article.READ, 0);
            getContentResolver().update(Feed.Article.CONTENT_URI, cv, 
                    Feed.Article.GROUP_ID + "=?", new String[]{String.valueOf(menuInfo.id)});
            break;
        }
        case R.id.group_list_contextmenu_update: {
            final Uri uri = ContentUris.withAppendedId(Feed.Group.CONTENT_URI, menuInfo.id);
            final Intent intent = new Intent(getApplication(), TransactionService.class);
            intent.putExtra(Transaction.EXTRA_TRANSACTION_TYPE, Transaction.TRANSACTION_TYPE_UPDATE_GROUP);
            intent.setData(uri);
            startService(intent);
        }
        default:
            break;
        }
        return true;
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.group_list, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.group_list_add: {
            startActivity(new Intent(getApplication(), AddGroupActivity.class));
            break;
        }
        case R.id.group_list_mark_all_as_read: {
            final ContentValues values = new ContentValues();
            values.put(Feed.Article.READ, 1);
            getContentResolver().update(Feed.Article.CONTENT_URI, values, null, null);
            break;
        }
        case R.id.group_list_mark_all_as_unread: {
            final ContentValues values = new ContentValues();
            values.put(Feed.Article.READ, 0);
            getContentResolver().update(Feed.Article.CONTENT_URI, values, null, null);
            break;
        }
        case R.id.group_list_import: {
            startActivity(new Intent(getApplication(), ImportFeedsActivity.class));
            break;
        }
        case R.id.group_list_update: {
            final Intent intent = new Intent(getApplication(), TransactionService.class);
            intent.putExtra(Transaction.EXTRA_TRANSACTION_TYPE, Transaction.TRANSACTION_TYPE_UPDATE_ALL);
            intent.setData(Feed.Source.ALL_FEEDS_URI);
            startService(intent);
            break;
        }
        default:
            break;
        }
        return true;
    }
    
    @Override
    public void onListItemClick(ListView listView, View view, int position, long id) {
        final Cursor cursor = (Cursor) listView.getItemAtPosition(position);
        final int groupId = cursor.getInt(Feed.Group.ID_INDEX);
        final Uri groupUri = ContentUris.withAppendedId(Feed.Group.CONTENT_URI, groupId);
        // mark this article as read
        final Intent intent = new Intent(getApplication(), FeedListActivity.class);
        intent.setData(groupUri);
        startActivity(intent);
        overridePendingTransition(R.anim.default_come_enter, R.anim.default_come_exit);
    }
    
    @Override
    public void onBackPressed() {
	super.onBackPressed();
	overridePendingTransition(R.anim.default_leave_enter, R.anim.default_leave_exit);
    }
    
    private void startAsyncQuery() {
        getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_INDETERMINATE_ON);
        mQueryHandler.startQuery(TOKEN_QUERY_ALL_GROUP, null,
                Feed.Group.CONTENT_URI, Feed.Group.PROJECTION, null, null, null);
    }
    
    private final class AsyncGroupQueryHandler extends AsyncQueryHandler {
        public AsyncGroupQueryHandler(ContentResolver cr) {
            super(cr);
        }
        
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            mListAdapter.changeCursor(cursor);
            getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_INDETERMINATE_OFF);
        }
        
        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {
            
        }
        
        @Override
        protected void onUpdateComplete(int token, Object cookie, int result) {
            
        }
        
        @Override
        protected void onInsertComplete(int token, Object cookie, Uri uri) {
            
        }
    }
    
    public class GroupListAdapter extends CursorAdapter {
        private static final String TAG = FeedSettings.GLOBAL_TAG;
        private LayoutInflater mFactory;
        
        private ArrayList<OnContentChangedListener> mListenerList;
        
        public GroupListAdapter(Context context, Cursor c) {
            super(context, c, false);
            mFactory = LayoutInflater.from(context);
            mListenerList = new ArrayList<OnContentChangedListener>();
        }

        public void addContentChangedListener(OnContentChangedListener listener) {
            assert(mListenerList == null);
            mListenerList.add(listener);
        }
        
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            assert(view == null);
            TextView title = (TextView) view.findViewById(R.id.group_list_item_title);
            TextView description = (TextView) view.findViewById(R.id.group_list_item_description);
            TextView count = (TextView) view.findViewById(R.id.group_list_item_count);
            title.setText(cursor.getString(Feed.Group.TITLE_INDEX));
            description.setText(cursor.getString(Feed.Group.DESCRIPTION_INDEX));
            final StringBuilder sb = new StringBuilder();
            sb.append(cursor.getString(Feed.Group.COUNT_UNREAD_INDEX));
            sb.append("/");
            sb.append(cursor.getString(Feed.Group.COUNT_INDEX));
            count.setText(sb.toString());
            if (cursor.getInt(Feed.Group.COUNT_UNREAD_INDEX) > 0) {
                count.setTextColor(Color.BLUE);
            } else {
                count.setTextColor(Color.BLACK);
            }
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            return mFactory.inflate(R.layout.group_list_item, null);
        }
        
        @Override
        protected void onContentChanged() {
//            Log.e(TAG, "group list somehting is changed, are you aware of that?");
            for (OnContentChangedListener listener : mListenerList) {
                listener.onContentChanged();
            }
        }
    }
}